#!/usr/bin/env bash

set -x
set -e

BIN_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

REPO_ROOT=$BIN_DIR/../..
cd $REPO_ROOT
swift run --package-path Scripts/translation-tool translation-tool download-resources

LOCALIZATION_ROOT=$REPO_ROOT/Signal/translations
cd $LOCALIZATION_ROOT

# Parse the PluralAware.stringsdict files to ensure they're not malformed.
lang_errors=()
for dir in *.lproj
do
  pushd "$dir"
  if [ -e PluralAware.stringsdict ]; then
    plutil PluralAware.stringsdict || lang_errors+=("$dir")
  fi
  popd
done
if [ "${#lang_errors[@]}" -gt 0 ]; then
  1>&2 echo "Some languages have malformed .stringsdict files: ${lang_errors[*]}"
  exit 1
fi

# Get and build iStringsCheck from https://github.com/signalapp/l10n_lint
# This does some checks to make sure all strings are present and that interpolated strings have the right number of arguments
LINT_CMD=$(command -v l10n_lint)
LINT_CMD=${LINT_CMD:-$REPO_ROOT/../l10n_lint/target/debug/l10n_lint}

if [ -e $LINT_CMD ]
then
  $LINT_CMD en.lproj/Localizable.strings .
  $LINT_CMD en.lproj/InfoPlist.strings .
else
  echo "Missing string linter. See: https://github.com/signalapp/l10n_lint"
  exit 1
fi

echo "Make sure you register any new localizations in XCode! (Go to Project > Signal > Localizations > Add Localizations)"
